import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Space, Tag, message, Modal, Form, Input, InputNumber, Select, Row, Col } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, SettingOutlined, SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import { 
  getConfigList, 
  createConfig,
  updateConfig,
  deleteConfig,
  type ProductConfig,
  type ConfigQueryParams,
  type CreateConfigRequest
} from '@/services/products';

const { Option } = Select;

const ProductConfigs: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [configs, setConfigs] = useState<ProductConfig[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingConfig, setEditingConfig] = useState<ProductConfig | null>(null);
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();

  // 表格列配置
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '配置名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      width: 250,
      ellipsis: true,
    },
    {
      title: '类别',
      dataIndex: 'category',
      key: 'category',
      width: 100,
      render: (category: string) => {
        const categoryMap = {
          gaming: { color: 'red', text: '游戏配置' },
          office: { color: 'blue', text: '办公配置' },
          design: { color: 'purple', text: '设计配置' },
          server: { color: 'green', text: '服务器配置' },
        };
        const config = categoryMap[category as keyof typeof categoryMap] || { color: 'default', text: category };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '总价格',
      dataIndex: 'total_price',
      key: 'total_price',
      width: 120,
      render: (price: any) => {
        const numPrice = typeof price === 'number' ? price : parseFloat(price) || 0;
        return `¥${numPrice.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
      },
    },
    {
      title: '性能评分',
      dataIndex: 'performance_score',
      key: 'performance_score',
      width: 100,
      render: (score: any) => {
        const numScore = typeof score === 'number' ? score : parseFloat(score) || 0;
        return (
          <Tag color={numScore >= 80 ? 'green' : numScore >= 60 ? 'orange' : 'red'}>
            {numScore}分
          </Tag>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (date: string) => new Date(date).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right' as const,
      width: 200,
      render: (record: ProductConfig) => (
        <Space>
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
          >
            查看
          </Button>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 获取配置列表
  const fetchData = async (page: number = currentPage, size: number = pageSize) => {
    try {
      setLoading(true);
      const searchValues = searchForm.getFieldsValue();
      
      const params: ConfigQueryParams = {
        page,
        limit: size,
        ...searchValues,
      };

      const response = await getConfigList(params);
      
      if (response.success) {
        setConfigs(response.data.items || []);
        setTotal(response.data.pagination.total);
        setCurrentPage(page);
        setPageSize(size);
      } else {
        message.error(response.message || '获取配置列表失败');
        setConfigs([]);
        setTotal(0);
      }
    } catch (error) {
      console.error('获取配置列表失败:', error);
      message.error('获取配置列表失败，请检查网络连接');
      setConfigs([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  };

  // 事件处理
  const handleSearch = () => {
    fetchData(1, pageSize);
  };

  const handleReset = () => {
    searchForm.resetFields();
    fetchData(1, pageSize);
  };

  const handleTableChange = (pagination: any) => {
    fetchData(pagination.current, pagination.pageSize);
  };

  const handleAdd = () => {
    setEditingConfig(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record: ProductConfig) => {
    setEditingConfig(record);
    form.setFieldsValue({
      name: record.name,
      description: record.description,
      category: record.category,
      total_price: typeof record.total_price === 'number' ? record.total_price : parseFloat(record.total_price) || 0,
      performance_score: typeof record.performance_score === 'number' ? record.performance_score : parseFloat(record.performance_score) || 0,
      image_url: record.image_url,
      components: JSON.stringify(record.components || {}, null, 2),
    });
    setModalVisible(true);
  };

  const handleView = (record: ProductConfig) => {
    const totalPrice = typeof record.total_price === 'number' ? record.total_price : parseFloat(record.total_price) || 0;
    const performanceScore = typeof record.performance_score === 'number' ? record.performance_score : parseFloat(record.performance_score) || 0;
    
    Modal.info({
      title: `配置详情: ${record.name}`,
      content: (
        <div>
          <p><strong>描述:</strong> {record.description || '暂无描述'}</p>
          <p><strong>类别:</strong> {record.category}</p>
          <p><strong>总价格:</strong> ¥{totalPrice.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</p>
          <p><strong>性能评分:</strong> {performanceScore}分</p>
          {record.image_url && (
            <p><strong>图片:</strong> <a href={record.image_url} target="_blank" rel="noopener noreferrer">查看图片</a></p>
          )}
          <p><strong>组件配置:</strong></p>
          <pre style={{ background: '#f5f5f5', padding: '10px', borderRadius: '4px', maxHeight: '300px', overflow: 'auto' }}>
            {JSON.stringify(record.components || {}, null, 2)}
          </pre>
        </div>
      ),
      width: 700,
    });
  };

  const handleDelete = (record: ProductConfig) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除配置 "${record.name}" 吗？`,
      onOk: async () => {
        try {
          await deleteConfig(record.id);
          message.success('删除成功');
          fetchData();
        } catch (error) {
          console.error('删除失败:', error);
          message.error('删除失败');
        }
      },
    });
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      
      // 解析组件JSON
      let components;
      try {
        components = JSON.parse(values.components);
      } catch (e) {
        message.error('组件配置格式错误，请输入有效的JSON');
        return;
      }

      const configData: CreateConfigRequest = {
        ...values,
        components,
      };

      if (editingConfig) {
        await updateConfig(editingConfig.id, configData);
        message.success('更新成功');
      } else {
        await createConfig(configData);
        message.success('创建成功');
      }
      
      setModalVisible(false);
      fetchData();
    } catch (error) {
      console.error('保存失败:', error);
      message.error('保存失败');
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <div className="p-6">
      <Card>
        <div className="mb-4 flex justify-between items-center">
          <h2 className="text-xl font-semibold flex items-center">
            <SettingOutlined className="mr-2" />
            配置管理
          </h2>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            添加配置
          </Button>
        </div>

        {/* 搜索表单 */}
        <Card className="mb-4" size="small">
          <Form form={searchForm} layout="inline">
            <Row gutter={[16, 16]} style={{ width: '100%' }}>
              <Col xs={24} sm={12} md={6}>
                <Form.Item name="keyword" label="关键词">
                  <Input placeholder="配置名称/描述" />
                </Form.Item>
              </Col>
              <Col xs={24} sm={12} md={6}>
                <Form.Item name="category" label="类别">
                  <Select placeholder="请选择类别" allowClear>
                    <Option value="gaming">游戏配置</Option>
                    <Option value="office">办公配置</Option>
                    <Option value="design">设计配置</Option>
                    <Option value="server">服务器配置</Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col xs={24} sm={12} md={6}>
                <Form.Item name="minPrice" label="最低价格">
                  <InputNumber placeholder="最低价格" style={{ width: '100%' }} />
                </Form.Item>
              </Col>
              <Col xs={24} sm={12} md={6}>
                <Form.Item>
                  <Space>
                    <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
                      搜索
                    </Button>
                    <Button icon={<ReloadOutlined />} onClick={handleReset}>
                      重置
                    </Button>
                  </Space>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Card>

        <Table
          columns={columns}
          dataSource={configs}
          loading={loading}
          rowKey="id"
          pagination={{
            current: currentPage,
            pageSize: pageSize,
            total: total,
            showTotal: (total) => `共 ${total} 条记录`,
            showSizeChanger: true,
            showQuickJumper: true,
            onChange: handleTableChange,
            pageSizeOptions: ['10', '20', '50', '100'],
          }}
          scroll={{ x: 1200 }}
          locale={{
            emptyText: (
              <div style={{ padding: '20px', textAlign: 'center' }}>
                <SettingOutlined style={{ fontSize: '48px', color: '#ccc', marginBottom: '16px' }} />
                <p style={{ color: '#999', marginBottom: '16px' }}>暂无配置数据</p>
                <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                  添加第一个配置
                </Button>
              </div>
            )
          }}
        />
      </Card>

      <Modal
        title={editingConfig ? '编辑配置' : '添加配置'}
        open={modalVisible}
        onOk={handleModalOk}
        onCancel={() => setModalVisible(false)}
        width={700}
        maskClosable={false}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="配置名称"
            rules={[{ required: true, message: '请输入配置名称' }]}
          >
            <Input placeholder="请输入配置名称" />
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
            rules={[{ required: true, message: '请输入描述' }]}
          >
            <Input.TextArea placeholder="请输入描述" rows={3} />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="category"
                label="类别"
                rules={[{ required: true, message: '请选择类别' }]}
              >
                <Select placeholder="请选择类别">
                  <Option value="gaming">游戏配置</Option>
                  <Option value="office">办公配置</Option>
                  <Option value="design">设计配置</Option>
                  <Option value="server">服务器配置</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="total_price"
                label="总价格"
                rules={[
                  { required: true, message: '请输入总价格' },
                  { type: 'number', min: 0.01, message: '总价格必须大于0' }
                ]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入总价格"
                  min={0}
                  precision={2}
                  formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                  parser={value => value!.replace(/¥\s?|(,*)/g, '') as any}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="performance_score"
                label="性能评分"
                rules={[
                  { required: true, message: '请输入性能评分' },
                  { type: 'number', min: 0, max: 100, message: '性能评分必须在0-100之间' }
                ]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入性能评分"
                  min={0}
                  max={100}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="image_url"
                label="图片URL"
              >
                <Input placeholder="请输入图片URL" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="components"
            label="组件配置 (JSON格式)"
            rules={[
              { required: true, message: '请输入组件配置' },
              {
                validator: (_, value) => {
                  if (!value) return Promise.resolve();
                  try {
                    JSON.parse(value);
                    return Promise.resolve();
                  } catch (e) {
                    return Promise.reject(new Error('请输入有效的JSON格式'));
                  }
                }
              }
            ]}
          >
            <Input.TextArea 
              placeholder={`请输入组件配置，例如：
{
  "cpu": "Intel Core i9-13900K",
  "gpu": "RTX 4090",
  "ram": "32GB DDR5",
  "storage": "2TB NVMe SSD"
}`}
              rows={8} 
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ProductConfigs; 